<template>
  <view>
    <u-navbar :background="background" :immersive="true" title=" " :border-bottom="false"></u-navbar>
    <u-swiper height="650" :autoplay="false" mode="number" img-mode="scaleToFill" indicator-pos="bottomRight"
      :list="info.images"></u-swiper>
    <view class="wrap">
      <view class="box">
        <view class="price n-flex-row n-justify-between n-align-center">
          <view class="qian">{{$t('¥')}}{{ Number(info.price).toFixed(2) }}</view>
          <view class="bi">{{ Number(info.integral).toFixed(2) }}{{$t('幸运币')}}</view>
        </view>
        <view style="margin-top: 10rpx; font-size: 32rpx">
          {{ info.title }}
        </view>
      </view>
      <view class="row-list">
        <view class="row">
          <view>{{$t('运费')}}</view>
          <view class="hui" v-if="info.freight_value == 0 || info.goods_type == 2">{{$t('免运费')}}</view>
          <view class="hui" v-else>{{$t('¥')}}{{ Number(info.freight_value).toFixed(2) }}</view>
        </view>
        <view class="row">
          <view>{{$t('库存')}}</view>
          <view class="hui">{{ info.stock }}</view>
        </view>
      </view>
      <view class="row-list-cell">
        <view class="row-list-cell-left">{{$t('服务保证')}}</view>
        <view class="row-list-cell-right">
          <view class="hui" v-if="info.goods_type == 2">{{$t('自动发卡商品品质保证无忧售后')}}</view>
          <view class="hui" v-else>{{$t('七天内发货品质保证无忧售后')}}</view>
        </view>
      </view>
      <view class="row-list-cell" @click="agreementShow = true">
        <view class="row-list-cell-left">{{$t('购前须知')}}</view>
        <view class="row-list-cell-right">
          <view class="hui">{{$t('不支持七天无理由退款')}}</view>
          <u-icon size="24" name="arrow-right" color="#999"></u-icon>
        </view>
      </view>
      <!--  -->

      <view class="info" style="margin-top: 10rpx">
        <view class="tit">
          <u-divider>{{$t('商品详情')}}</u-divider>
        </view>
        <view class="goods_content">
          <u-parse :html="info.content"></u-parse>
        </view>
      </view>
    </view>

    <view class="gao"></view>

    <view class="btm">
      <view class="btmbox">
        <!-- #ifndef MP-WEIXIN -->
        <view class="kefu n-shrink-0" @click="wxKefu">
          <image src="../../static/image/m_.png" mode="aspectFit"></image>
          <view style="color: #666">{{$t('客服')}}</view>
        </view>
        <!-- #endif -->

        <!-- #ifdef MP-WEIXIN -->
        <button class="kefu kefubtn n-shrink-0" open-type="contact">
          <image src="../../static/image/m_.png" mode=""></image>
          <view style="color: #666">{{$t('客服')}}</view>
        </button>
        <!-- #endif -->

        <view class="btn buy-btn">
          <view class="buy-btn-0" @click="openBuy(1)">{{$t('幸运币兑换')}}</view>
<!--          <view class="buy-btn-1" @click="openBuy(2)">{{$t('立即购买')}}</view> -->
          <!-- 	<button class="huan" @click="show = true;isBuy = true" style="width: 100%;">立即购买</button> -->
        </view>
      </view>
    </view>

    <u-popup v-model="show" @close="close" mode="bottom" :safe-area-inset-bottom="true">
      <view class="buybox">
        <view class="goods n-flex-row">
          <view class="picbox">
            <image :src="info.goodsPic" mode=""></image>
          </view>
          <view class="textbox">
            <view class="price" v-if="buyType == 2">
              {{$t('¥')}}
              <text>{{ Number(info.price).toFixed(2) }}</text>
            </view>
            <view class="price" v-if="buyType == 1">
              <text>{{ Number(info.integral).toFixed(2) }}</text>
              {{$t('幸运币')}}
            </view>
            <!-- <view class="price" style="color: #FC7802;"><text>{{info.integral}}</text>幸运币</view> -->
            <view class="stock">{{$t('库存')}}：{{ info.stock }}{{$t('件')}}</view>
          </view>
        </view>
        <!-- <view class="xinghao">
					<view class="tit">型号</view>
					<view class="xhList">
						<view class="list active">128GB</view>
						<view class="list">256GB</view>
						<view class="list">512GB</view>
					</view>
				</view> -->
        <view class="selectNum">
          <view class="">{{$t('购买数量')}}</view>
          <u-number-box v-model="num" :min="1" :max="info.stock" @change="valChange"></u-number-box>
        </view>

        <button class="buy btn" v-if="isBuy && buyType == 2" @click="buy">
          {{$t('立即购买')}}
        </button>
        <button class="buy btn" v-if="isBuy && buyType == 1" @click="buy">
          {{$t('立即兑换')}}
        </button>
      </view>
    </u-popup>
    <kefuTel :isShow="kfshow" ref="child" @cusEvent="hide"></kefuTel>

    <u-popup v-model="agreementShow" @close="agreementShow = false" mode="center" :safe-area-inset-bottom="true">
      <view class="agreement-view">
        <!-- <view class="agreement-view-view"> -->
        <view class="agreement-view-title">{{ deliveryRuleTextTitle }}</view>
        <scroll-view :scroll-top="0" scroll-y="true" class="scroll-rule-Y">
          <u-parse :html="deliveryRuleText"></u-parse>
        </scroll-view>
        <!-- </view> -->
        <view class="agreement-view-btn" @click="agreementShow = false">{{$t('知道了')}}</view>
      </view>
    </u-popup>
    <uni-popup ref="popupLimits" type="top" heigth="200" :is-mask-click="false" @maskClick="popupClcik">
      <view class="qweqwe">
        <view>{{$t('申请手机或耳机的麦克风权限')}}</view>
        <view>{{$t('申请相册权限')}}</view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
// #ifdef APP-PLUS
var qiyuModule = uni.requireNativePlugin("Netease-QiyuModule");
const modal = uni.requireNativePlugin("modal");
import { qy_appKey } from "@/utils/keyControl.js";
// #endif
import kefuTel from "@/components/kefuTel.vue";
export default {
  data() {
    return {
      background: {
        backgroundColor: "",
      },
      agreementShow: false,
      show: false,
      num: 1,
      isBuy: true,
      id: "",
      info: "",
      kfshow: false,
      bi: 0,
      deliveryRuleText: "",
      deliveryRuleTextTitle: "",
      buyType: 1, // 1幸运币 2 立即购买
    };
  },
  components: {
    kefuTel,
  },
  onPageScroll(e) {
    if (e.scrollTop >= 150) {
      this.background.backgroundColor = "#fff";
    } else {
      this.background.backgroundColor = "";
    }
  },
  onLoad(option) {
    this.id = option.id;
    this.getInfo();
    if (uni.getStorageSync("user")) {
      this.getBi();
    }
    this.getDeliveryRuleText();
  },
  methods: {
    //获取ip
    getIp() {
      this.$http({
        url: "api/Ios/get_ip",
      })
        .then((res) => {
          if (res.data.code == 1) {
            //res.data.data.ip
            return res.data.data.clear;
          }
        })
        .catch((err) => { });
    },
    /* 初始化七鱼 */
    initSetUserInfo() {
      let userInfo = uni.getStorageSync("user");
      const { id, username, mobile, image, create_time, update_time } =
        userInfo;
      qiyuModule.initSdk({
        appKey: qy_appKey,
        appName: "叮当盲盒",
        pkCerName: "PushKit推送证书名；对应云信的pkCername",
      });
      qiyuModule.setUserInfo(
        {
          userId: id || this.getIp(),
          data: JSON.stringify([
            {
              key: "real_name",
              value: username ? username : '',
            },
            {
              key: "mobile_phone",
              hidden: true,
              value: mobile ? mobile : '',
            },

            {
              key: "avatar",
              value: image ? image : 'https://qiyukf.com/def_avatar.png'
            },
            {
              index: 5,
              key: "reg_date",
              label: "注册日期",
              value: create_time ? create_time : '',
            },
            {
              index: 6,
              key: "last_login",
              label: "上次登录时间",
              value: update_time ? update_time : '',
            },
          ]),
        },
        (ret) => {
          console.log("js打印" + JSON.stringify(ret));
        }
      );
      qiyuModule.updateOptions(
        {
          isPullMessageFromServer: false,
          uiCustomization: {
            hideLeftAvatar: false,
            isShowTitleAvatar: true,
            hideRightAvatar: false,
            inputTextColor: "#ff5500",
          },
        },
        (url) => {
          //点击url的回调
          plus.runtime.openWeb(url);
        }
      );
      qiyuModule.setFinishPageSwitch(true);
      qiyuModule.setPermissionCallback((retCallback) => {
        //麦克风
        let value1 = uni.getStorageSync("is_KEFU_RECORD_AUDIO");
        if (value1 != 1) {
          this.$refs.popupLimits.open();
        }
        plus.android.requestPermissions(
          [
            "android.permission.RECORD_AUDIO",
            "android.permission.MODIFY_AUDIO_SETTINGS",
          ],
          function (e) {
            if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启
              console.log("权限被永久拒绝" + e.deniedAlways.toString());
              this.$refs.popupLimits.close();
              uni.setStorageSync("is_KEFU_RECORD_AUDIO", 2);
            }
            if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
              console.log("权限被临时拒绝" + e.deniedPresent.toString());
              this.$refs.popupLimits.close();
              uni.setStorageSync("is_KEFU_RECORD_AUDIO", 0);
            }
            if (e.granted.length > 0) {
              //权限被允许
              console.log("权限被允许" + e.granted.toString());
              this.$refs.popupLimits.close();
              uni.setStorageSync("is_KEFU_RECORD_AUDIO", 1);
            }
          },
          function (e) {
            console.log("Request Permissions error:" + JSON.stringify(e));
            uni.showToast({
              title: "Request Permissions error:" + JSON.stringify(e),
            });
          }
        );
        //相机 相册
        let value2 = uni.getStorageSync("is_KEFU_CAMERA");
        if (value2 != 1) {
          this.$refs.popupLimits.open();
        }
        plus.android.requestPermissions(
          [
            "android.permission.CAMERA",
            "android.permission.READ_EXTERNAL_STORAGE",
          ],
          function (e) {
            if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启
              console.log("权限被永久拒绝" + e.deniedAlways.toString());
              this.$refs.popupLimits.close();
              uni.setStorageSync("is_KEFU_CAMERA", 2);
            }
            if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
              console.log("权限被临时拒绝" + e.deniedPresent.toString());
              this.$refs.popupLimits.close();
              uni.setStorageSync("is_KEFU_CAMERA", 0);
            }
            if (e.granted.length > 0) {
              //权限被允许
              console.log("权限被允许" + e.granted.toString());
              this.$refs.popupLimits.close();
              uni.setStorageSync("is_KEFU_CAMERA", 1);
            }
          },
          function (e) {
            console.log("Request Permissions error:" + JSON.stringify(e));
            uni.showToast({
              title: "Request Permissions error:" + JSON.stringify(e),
            });
          }
        );
        //文件存储
        let value3 = uni.getStorageSync("is_KEFU_FILE");
        if (value3 != 1) {
          this.$refs.popupLimits.open();
        }
        plus.android.requestPermissions(
          [
            "android.permission.MANAGE_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE",
          ],
          function (e) {
            if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启
              console.log("权限被永久拒绝" + e.deniedAlways.toString());
              this.$refs.popupLimits.close();
              uni.setStorageSync("is_KEFU_FILE", 2);
            }
            if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
              console.log("权限被临时拒绝" + e.deniedPresent.toString());
              this.$refs.popupLimits.close();
              uni.setStorageSync("is_KEFU_FILE", 0);
            }
            if (e.granted.length > 0) {
              //权限被允许
              console.log("权限被允许" + e.granted.toString());
              this.$refs.popupLimits.close();
              uni.setStorageSync("is_KEFU_FILE", 1);
            }
          },
          function (e) {
            console.log("Request Permissions error:" + JSON.stringify(e));
            uni.showToast({
              title: "Request Permissions error:" + JSON.stringify(e),
            });
          }
        );
      });
    },
    //企业微信客服
    wxKefu() {
		this.kfshow = true;
      // this.$http({
      //   url: "api/member/get_weixin_state",
      //   data: {},
      // })
      //   .then((res) => {
      //     if (res.data.code == 1) {
      //       let obj = res.data.data;
      //       if (obj.weixin_kefu == 1) {
      //         uni.navigateTo({
      //           url: "/pagesA/pages/my/wecom",
      //         });
      //       } else {
      //         this.startQiyu();
      //       }
      //     } else {
      //       this.$tip.tip(res.data.msg);
      //     }
      //   })
      //   .catch((err) => { });
    },
    // 联系客服
    startQiyu() {
      qiyuModule.openServiceActivity({
        title: this.$t("官方客服"),
        source: {
          title: this.$t("官方客服"),
          robotId: 5395052,
        },
        openMode: "push",
      });
    },
    popupClcik() {
      this.$refs.popupLimits.close();
      this.startQiyu();
    },
    openBuy(type) {
      this.show = true;
      this.isBuy = true;
      this.buyType = type;
    },
    hide() {
      this.kfshow = false;
    },
    getDeliveryRuleText() {
      this.$http({
        url: "api/common/get_agreement",
        data: {
          name: "delivery_rule",
        },
      })
        .then((res) => {
          console.log(res);
          if (res.data.code == 1) {
            this.deliveryRuleText = res.data.data.content;
            this.deliveryRuleTextTitle = res.data.data.title;
          } else {
            this.$tip.tip(res.data.msg);
          }
        })
        .catch((err) => { });
    },
    buy() {
      var data = {
        type: 1,
        id: this.info.id,
        image: this.info.goodsPic,
        name: this.info.title,
        num: this.num,
        price: this.info.price,
        integral: this.info.integral,
        freight_value: this.info.freight_value,
        goods_type: this.info.goods_type,
        buyType: this.buyType,
      };
      uni.setStorageSync("goods", data);
      uni.navigateTo({
        url: "/pages/mall/confirmOrder",
      });
    },
    getBi() {
      this.$http({
        url: "api/member/get_user_info",
      })
        .then((res) => {
          if (res.data.code == 1) {
            this.bi = res.data.data.integral;
            uni.setStorageSync("user", res.data.data);
            uni.$emit("updataUser");
          }
        })
        .catch((err) => { });
    },
    getInfo() {
      this.$http({
        url: "api/common/get_goods_info",
        data: {
          id: this.id,
        },
      })
        .then((res) => {
          if (res.data.code == 1) {
            this.info = res.data.data;
            this.info.freight_value = parseInt(
              res.data.data.freight_value
            ).toFixed(2);
            this.info.goodsPic = this.info.images[0];
          }
        })
        .catch((err) => { });
    },
    formatRichText(html) {
      if (!html) {
        return;
      }
      let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
        match = match
          .replace(/style="[^"]+"/gi, "")
          .replace(/style='[^']+'/gi, "");
        match = match
          .replace(/width="[^"]+"/gi, "")
          .replace(/width='[^']+'/gi, "");
        match = match
          .replace(/height="[^"]+"/gi, "")
          .replace(/height='[^']+'/gi, "");
        return match;
      });
      newContent = newContent.replace(
        /style="[^"]+"/gi,
        function (match, capture) {
          match = match
            .replace(/width:[^;]+;/gi, "width:100%;")
            .replace(/width:[^;]+;/gi, "width:100%;");
          return match;
        }
      );
      newContent = newContent.replace(/<br[^>]*\/>/gi, "");
      newContent = newContent.replace(
        /\<img/gi,
        '<img style="width:100%;height:auto;display:block;"'
      );
      return newContent;
    },
    valChange(e) {
      console.log("当前值为: " + e.value);
    },
    // 弹出层收起
    close() {
      this.num = 1;
    },
  },
};
</script>

<style lang="scss" scoped>
@import url("../../static/css/goodsInfo.css");

.row {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #fff;
  width: 100%;
}

.hui {
  color: #999;
  font-size: 26rpx;
}

.row .pri {
  font-size: 34rpx;
  font-weight: bold;
}

.row-list {
  display: flex;
  // margin-bottom: 20rpx;
}

.row-list-cell {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #fff;
  width: 100%;
  margin-top: 1rpx;
}

.row-list-cell-right {
  display: flex;
  align-items: center;

  .u-icon {
    margin-left: 16rpx;
  }
}

.agreement-view {
  width: 580rpx;
  height: 800rpx;
  background-color: #845ec2;
  border-radius: 40rpx;
  overflow: hidden;

  .agreement-view-btn {
    width: 540rpx;
    background-color: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    font-size: 30rpx;
    color: #845ec2;
    height: 80rpx;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 50rpx;
  }
}

.agreement-view-title {
  height: 100rpx;
  line-height: 100rpx;
  font-size: 30rpx;
  text-align: center;
  color: #fff;
}

.scroll-rule-Y {
  height: 500rpx;
  padding: 0rpx 30rpx;
  box-sizing: border-box;
  margin: 6rpx auto;
  color: #fff;
}

.buy-btn {
  display: flex;
  width: 100%;
  justify-content: space-between;

  .buy-btn-0 {
    background-color: #e09250;
    color: #fff;
    width: 520rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .buy-btn-1 {
    background-color: #000;
    color: #fff;
    width: 260rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .qweqwe {
    background-color: #fff;
    height: 150rpx;
    width: 100%;
    color: #000;
    margin-top: 25%;
    padding: 20rpx;
    box-sizing: border-box;
  }
}
</style>
